/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.ufes.cwtools.joinus.R;
import android.location.Location;
import android.util.Log;

public class ServerCom {
	// Configurar aqui o endereço do JoinUs-ApplicationServer.
	public static final String HOST = "joinus.inf.ufes.br";
	public static final int PORT = 80;
	public static final int SSL_PORT = 443;
	public static final int CERTIFICATE = R.raw.certificate;
	
	//Chave do Google Maps
	public static final String GOOGLE_MAPS_KEY = "03ukYISgJA1Ff7E9UdnxHB2_m4NCA7TbGO_C2Fw";
	
	static public String id = null;
	static public String key = null;

	static private Socket SSLSocket;
	static private BufferedWriter bw;
	static private BufferedReader br;

	static final public int OK = 0;
	static final public int SERVER_ERROR = 1;
	static final public int SSL_ERROR = 2;
	static final public int INVALID_USER = 4;

	static private SSLContext sc = null;
	static private Socket clientSocket = null;
	static private BufferedWriter clientOut = null;
	static private BufferedReader clientIn = null;
	static private Resources r;

	static public void initResources(Resources rr) {
		r = rr;
	}

	static public String getMyId() {
		return id;
	}
	
	static public int setPollingCom() {
		try {
			clientSocket = new Socket(HOST, PORT);
			clientOut = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()), 8192);
			clientIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()), 8192);
		} catch (Exception e) {
			Log.e("POOLERROR", e.toString());
			return SERVER_ERROR;
		}
		return OK;
	}

	static public int setSSLContext()
	{
		try {
			InputStream ris = r.openRawResource(CERTIFICATE);
			CertificateFactory cf = CertificateFactory.getInstance("X.509");
			X509Certificate cert = (X509Certificate) cf.generateCertificate(ris);

			KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
			ks.load(null);
			ks.setCertificateEntry("cert", cert);

			String ka = KeyManagerFactory.getDefaultAlgorithm();
			String ta = TrustManagerFactory.getDefaultAlgorithm();

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(ka);
			TrustManagerFactory tmf = TrustManagerFactory.getInstance(ta);

			kmf.init(ks, null);
			tmf.init(ks);

			KeyManager[] kms = kmf.getKeyManagers();
			TrustManager[] tms = tmf.getTrustManagers();

			sc = SSLContext.getInstance("TLS");
			sc.init(kms, tms, new java.security.SecureRandom());

			SSLSocket = sc.getSocketFactory().createSocket(HOST, SSL_PORT);
			
			bw = new BufferedWriter(new OutputStreamWriter(SSLSocket.getOutputStream()), 8192);
			br = new BufferedReader(new InputStreamReader(SSLSocket.getInputStream()), 8192);
		} catch (Exception e) {
			Log.e("SSL", "", e);
			return SSL_ERROR;
		}
		return OK;
	}

	static public int createUser(String username, String password, String requester, String xml)
	{
		if (setSSLContext() == SSL_ERROR)
			return SSL_ERROR;

		try {
			bw.append("GET /JoinUs-ApplicationServer/servlets/Login?action=new&login=" + username
					+ "&password=" + password + "\n");
			bw.append("Host: " + HOST + ":" + PORT + "\n\n");
			bw.flush();
		
			String response = br.readLine();
			if (response.compareTo("ok") != 0) {
				SSLSocket.close();
				return INVALID_USER;
			}
			id = br.readLine();
			key = br.readLine();
			SSLSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
			return SERVER_ERROR;
		}

		return OK;
	}
	
	static public int authUser(String username, String password, String requester)
	{
		if (setSSLContext() == SSL_ERROR) return SSL_ERROR;
		
		try {
			bw.append("GET /JoinUs-ApplicationServer/servlets/Login?action=login&login="
					+ username + "&password=" + password + "\n");
			bw.append("Host: " + HOST + ":" + PORT + "\n\n");
			bw.flush();
			
			String r = br.readLine();
			if (r.compareTo("ok") != 0) {
				SSLSocket.close();
				Log.d("SERVERCOM", "Usuário inválido.");
				return INVALID_USER;
			}
			id = br.readLine();
			key = br.readLine();
			SSLSocket.close();
		} catch (Exception e) {
			Log.d("SERVERCOM", "ERRO: " + e.getMessage());
			return SERVER_ERROR;
		}
		return OK;
	}

	static public String getInvitations(String username, String password,
		String latitude, String longitude)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;
		long posX=Integer.parseInt(latitude);
		long posY=Integer.parseInt(longitude);

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getInvitations");
		m.put("login", username);
		m.put("password", password);
		m.put("posX", posX/1000000+"."+Math.abs(posX%1000000));
		m.put("posY", posY/1000000+"."+Math.abs(posY%1000000));

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			String msg = URLEncoder.encode(Crypter.encrypt(key, m));
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + id + "&msg=" + msg
					+ "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
		} catch (Exception e) {
			Log.e("ERROR", e.toString());
			return null;
		}

		StringBuilder i = new StringBuilder();
		String cl = null;
		try {
			cl = pr.readLine();
			if (cl.compareTo("ok") != 0) {
				ps.close();
				return "SERVER_ERROR";
			}
			while ((cl = pr.readLine()) != null) {
				i.append(cl);
			}
			ps.close();
		} catch (Exception e) {
			Log.d("DEBUG", i.toString());
			return null;
		}
		return i.toString();
	}

	static public String getLocation(long id)
	{
		StringBuilder GPS = new StringBuilder();
		String cl = null;

		try {
			clientOut.append("GET"
				+ " /JoinUs-LocationManager/Dispatcher?function=GetLocation&id="
				+ id + " HTTP/1.1\n");
			clientOut.append("Host: " + HOST + ":" + PORT + "\n");
			clientOut.append("Connection: Keep-Alive\n\n");
			clientOut.flush();
			int i = 0;
			for (i = 0; i < 4; i++) {
				cl = clientIn.readLine();
				Log.d("GPSRESPONSE", cl);
			}

			cl = clientIn.readLine();
			cl = clientIn.readLine();
			Log.d("GPSFINALRESPONSE", cl + ".");
			GPS.append(cl);

		} catch (Exception e) {
			Log.d("ERROLOCATIONS", e.toString());
			return null;
		}

		return GPS.toString();
	}

	static public String pollingGetInvitations(String username,
		String password, String latitude, String longitude)
	{
		Map<String, String> m = new HashMap<String, String>();

		long posX=Integer.parseInt(latitude);
		long posY=Integer.parseInt(longitude);
		
		m.put("action", "getInvitations");
		m.put("login", username);
		m.put("password", password);
		m.put("posX", posX/1000000+"."+Math.abs(posX%1000000));
		m.put("posY", posY/1000000+"."+Math.abs(posY%1000000));

		try {
			clientOut.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id="
					+ id + "&msg=" + URLEncoder.encode(Crypter.encrypt(key, m))
					+ " HTTP/1.1\n");
			clientOut.append("Host: " + HOST + ":" + PORT + "\n");
			clientOut.append("Connection: Keep-Alive\n\n");
			clientOut.flush();
		} catch (Exception e) {
			return null;
		}
		StringBuilder i = new StringBuilder();
		try {

			String cl = null;
			int it = 0;
			for (it = 0; it < 6; it++) {
				cl = clientIn.readLine();
				Log.d("INVIRESPONSE", cl);
			}

			cl = clientIn.readLine();
			if (cl.compareTo("ok") != 0) {
				Log.d("DEBUG", cl);
				return null;
			}
			while (clientIn.ready()) {
				cl = clientIn.readLine();
				i.append(cl);
			}
		} catch (Exception e) {
			Log.d("DEBUG", e.toString());
			return null;
		}
		Log.d("GETINTRET", ">"+i.toString());
		return i.toString();
	}

	static public String getCampaigns(String username, String password)
	{
		Socket ps;
		BufferedWriter plainWriter;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getCampaigns");
		m.put("login", username);
		m.put("password", password);

		try {
			ps = new Socket(HOST, PORT);
			plainWriter = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			plainWriter.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + id
					+ "&msg=" + URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			plainWriter.append("Host: " + HOST + ":" + PORT + "\n\n");
			plainWriter.flush();
		} catch (Exception e) {
			return null;
		}

		StringBuilder c = new StringBuilder();
		String cl = null;

		try {
			if ((pr.readLine()).compareTo("ok") != 0) {
				while ((cl = pr.readLine()) != null) {
					Log.d("GETCAMP", cl);
					c.append(cl);
				}
				Log.d("GETCAMP", "pau!");
				ps.close();
				return "SERVER_ERROR";
			}
			while ((cl = pr.readLine()) != null) {
				Log.d("GETCAMP", cl);
				c.append(cl);
			}
			ps.close();
		} catch (Exception e) {
			Log.d("GETCAMP", "pau!");
			return null;
		}

		return c.toString();
	}

	static public int updateUser(String username, String password,
			String requester, String xml)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "update");
		m.put("xml", xml);
		
		Log.d("UPDATE", xml);
		Log.d("UPDATE", id + "");
		Log.d("UPDATE", key + "");
		
		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Profile?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			
			Log.d("UPDATE",URLEncoder.encode(Crypter.encrypt(key, m)));
			
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			String log;
			if ((log=pr.readLine()).compareTo("ok") != 0) {
				Log.d("UPDATE",log);
				return SERVER_ERROR;
			}
			Log.d("UPDATE",log);
			while((log=pr.readLine())!=null){
				Log.d("UPDATE",log);
			}
			//ps.close();
		} catch (Exception e) {
			return SERVER_ERROR;
		}

		return OK;
	}

	static public String getAction(String username, String password, String requester) {
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "get");
		m.put("login", username);
		m.put("password", password);
		m.put("request", requester);

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Profile?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
		} catch (Exception e) {
			return null;
		}

		StringBuilder p = new StringBuilder();
		String cl;

		try {
			if ((pr.readLine()).compareTo("ok") != 0) {
				ps.close();
				return "SERVER_ERROR";
			}
			while ((cl = pr.readLine()) != null) {
				p.append(cl);
			}
			ps.close();
		} catch (Exception e) {
			return null;
		}

		return p.toString();
	}

	static public String getAttachments(String idCampaign)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();
		m.put("idCampaign", idCampaign);
		m.put("action", "getAttachments");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + ServerCom.id
					+ "&msg=" + URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
		} catch (Exception e) {
			Log.d("DEBUG", e.toString());
			return "SERVER_ERROR";
		}

		StringBuilder cc = new StringBuilder();
		String cl = null;

		try {
			String response = pr.readLine();
			if (response.compareTo("ok") != 0) {
				Log.d("CREATEERROR1", "Create error1"+response);
				while (pr.ready()) {
					Log.d("CREATEERROR2", "Create error2"+pr.readLine());	
				}
				return "SERVER_ERROR";
			}
			
			while ((cl = pr.readLine()) != null) cc.append(cl);
			
			ps.close();
		} catch (Exception e) {
			Log.d("DEBUG", e.toString());
			return "SERVER_ERROR";
		}

		return cc.toString();
	}
	
	static public int creteCampAction(String username, String password,
			String requester, long posX, long posY, long radius, String desc,
			String expi, String campName, int type)
	{
		int id = -1;
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "createCampaign");
		m.put("login", username);
		m.put("password", password);
		m.put("request", requester);
		m.put("posX", ((double)posX)/1000000+"");
		m.put("posY", ((double)posY)/1000000+"");
		m.put("radius", ((double)radius)/1000000+"");
		m.put("public", type+"");
		
		m.put("description", desc);
		m.put("expiration", expi);
		m.put("name", campName);

		Log.d("COORDS",((double)posX)/1000000+"/"+((double)posY)/1000000+"/"+((double)radius)/1000000+"");
		
		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + ServerCom.id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
		} catch (Exception e) {
			Log.d("DEBUG", "Create error1");
			return SERVER_ERROR;
		}

		StringBuilder cc = new StringBuilder();
		String cl = null;

		try {
			String response = pr.readLine();
			if (response.compareTo("ok") != 0) {
				Log.d("CREATEERROR1", "Create error1"+response);
				while(pr.ready()){
					Log.d("CREATEERROR2", "Create error2"+pr.readLine());	
				}
				return SERVER_ERROR;
			}
			
			while ((cl = pr.readLine()) != null) {
				id=Integer.parseInt(cl);
				cc.append(cl);
			}
			ps.close();
		} catch (Exception e) {
			Log.d("DEBUG", "Create error3");
			return SERVER_ERROR;
		}

		Log.d("DEBUG", "CREATE OK" + cc.toString());
		return id;
	}

	static public String joinCampaign(String username, String password,
			long campId) {
		Log.d("Join",campId+"");
		
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "joinCampaign");
		m.put("login", username);
		m.put("password", password);
		m.put("idCampaign", campId + "");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
		} catch (Exception e) {
			return null;
		}

		StringBuilder jc = new StringBuilder();
		String cl;

		try {
			if (pr.readLine().compareTo("ok") != 0)
				return null;
			cl = pr.readLine();
			while ((cl = pr.readLine()) != null) {
				jc.append(cl);
			}
			ps.close();
		} catch (Exception e) {
			return null;
		}

		Log.d("DEBUG", "****** JOIN ***** " + jc.toString());
		return "OK";
	}

	static public String getUpdates(String username, String password)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getUpdates");
		m.put("login", username);
		m.put("password", password);

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
		} catch (Exception e) {
			return null;
		}

		StringBuilder u = new StringBuilder();
		String cl = null;

		try {
			if (pr.readLine().compareTo("ok") != 0)
				return "SERVER_ERROR";
			while ((cl = pr.readLine()) != null){
				u.append(cl);
			}
		} catch (Exception e) {
			return null;
		}

		return u.toString();
	}
	
	public static boolean createCommu(String commuName, String commuDesc, String commuCreator, int type, int cate){
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "create");
		m.put("name", commuName);
		m.put("description", commuDesc);
		m.put("type", type+"");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			while ((cl = pr.readLine()) != null){
				Log.d("CREATECOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("CREATECOMMUERROR",e.toString());
			return false;
		}	
		return true;
		
	}
	
	public static String getCommu(){
		String cl = null;
		StringBuilder sb= new StringBuilder();
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getJoined");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("JOINEDCOMMUERROR",cl);
				}
				return null;
			}
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("JOINEDCOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("JOINEDCOMMUERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	public static String joinCommu(String idc)
	{
		String cl = null;
		StringBuilder sb= new StringBuilder();
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "join");
		m.put("idCommunity", idc);
		
		Log.d("JOINCOMMU","id:"+idc);

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("JOINCOMMUERROR",cl);
				}
				return null;
			}
			
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("JOINCOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("JOINCOMMUERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	public static String searchCommu(String query){
		String cl = null;
		StringBuilder sb= new StringBuilder();
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "search");
		m.put("name", query);

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("SEARCHCOMMUERROR",cl);
				}
				return null;
			}
			
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("SEARCHCOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("SEARCHCOMMUERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}

	public static boolean quitCommu(String toQuit, String target) {
		String cl = null;
		StringBuilder sb= new StringBuilder();
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "quit");
		m.put("idCommunity", toQuit);
		if(target.compareTo(id+"")!=0){
			Log.d("QC","self");
			m.put("target", target);
		}

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("QUITCOMMUERROR",cl);
				}
				return false;
			}
			
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("QUITCOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("QUITCOMMUERROR",e.toString());
			return false;
		}	
		return true;
		
	}
	
	public static String gtCommu(String commuId){
		String cl = null;
		StringBuilder sb= new StringBuilder();
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getData");
		m.put("idCommunity", commuId);

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("GETCOMMUERROR",cl);
				}
				return null;
			}
			
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("GETCOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("GETCOMMUERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}

	public static String listCommuMembers(String commuId) {
		String cl = null;
		StringBuilder sb= new StringBuilder();
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getData");
		m.put("idCommunity", commuId);

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("GETCOMMUERROR",cl);
				}
				return null;
			}
			
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("GETCOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("GETCOMMUERROR",e.toString());
			return null;
		}	
		return sb.toString();
		
	}

	public static boolean editComu(long commuId, String commuName, String commuDesc, int type) {
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "edit");
		m.put("name", commuName);
		m.put("description", commuDesc);
		m.put("type", type+"");
		m.put("idCommunity", commuId+"");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Community?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			while ((cl = pr.readLine()) != null){
				Log.d("EDITCOMMU",cl);
			}
			
		} catch (Exception e) {
			Log.d("EDITCOMMUERROR",e.toString());
			return false;
		}	
		return true;
	}
	
	public static String searchContacts(String query) {
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "searchUser");
		m.put("q", query);
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Contact?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if (pr.readLine().compareTo("ok") != 0) {
				while ((cl = pr.readLine()) != null) {
					sb.append(cl);
					Log.d("SEARCHERROR", cl);
				}
				return null;
			}
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("SEARCHCON", cl);
			}
			
		} catch (Exception e) {
			Log.d("SEARCHERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	public static String getContactInfo(String idPro)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getProfile");
		m.put("idProfile", idPro);
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Profile?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			
			Log.d("teste", pw.toString());
			pw.flush();
			
			String cl = null;
			
			if (pr.readLine().compareTo("ok") != 0) {
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("GETPROERROR",cl);
				}
				return null;
			}
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("GETPRO",cl);
			}
			
		} catch (Exception e) {
			Log.d("GETPROERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	public static boolean addContact(String idPro)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "addUser");
		m.put("id", idPro);
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Contact?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if (pr.readLine().compareTo("ok") != 0) {
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("ADDCONERROR",cl);
				}
				return false;
			}
						
			while ((cl = pr.readLine()) != null) {
				sb.append(cl);
				Log.d("ADDCON",cl);
			}
			
		} catch (Exception e) {
			Log.d("ADDCONERROR",e.toString());
			return false;
		}	
		return true;
	}
	
	public static String getContacts()
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getUsers");
		StringBuilder sb= new StringBuilder("");
		
		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Contact?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
//			Log.d("GETCON",key);
//			Log.d("GETCON",id);
//			Log.d("GETCON",URLEncoder.encode(Crypter.encrypt(key, m)));
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("GETCONTERROR",cl);
				}
				return null;
			}
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
//				Log.d("GETCONT",cl);
			}
			
		} catch (Exception e) {
			Log.d("GETCONTERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}

	public static boolean deleteContact(String delID)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "removeUser");
		m.put("id", delID);
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Contact?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("DELCONERROR",cl);
				}
				return false;
			}
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("DELCON",cl);
			}
			
		} catch (Exception e) {
			Log.d("DELCONERROR",e.toString());
			return false;
		}	
		return true;		
		
	}
	
	public static boolean sendMsg(String toID, String msg)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "send");
		m.put("id", toID);
		m.put("msg", msg);
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Message?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("SENDMSGERROR",cl);
				}
				return false;
			}
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("SENDMSG",cl);
			}
			
		} catch (Exception e) {
			Log.d("SENDMSGERROR",e.toString());
			return false;
		}	
		return true;		
	}
	
	public static String getMsgs(){
		return getMsgsAndUpdatePosition(null);
	}

	public static String getMsgsAndUpdatePosition(Location pos)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();
		m.put("action", "get");
		
		String updatePos = "false";
		
		if(pos != null){
			m.put("lat", Double.toString(pos.getLatitude()));
			m.put("lng", Double.toString(pos.getLongitude()));
			updatePos = "true";
		}
		m.put("updatePos", updatePos);
		
		StringBuilder sb = new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Message?id=" + id
				+ "&msg=" + URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			if (pr.readLine().compareTo("ok") != 0) {
				while ((cl = pr.readLine()) != null) {
					sb.append(cl);
					Log.e("XMLCon", "Not OK! Dumping...");
					Log.d("GETCONTERROR", cl);
				}
				return null;
			}
			
			while ((cl = pr.readLine()) != null) {
				sb.append(cl);
			}
		} catch (Exception e) {
			Log.d("GETCONTERROR", e.toString());
			return null;
		}
		return sb.toString();
	}
	
	public static String getContactInfoLite(String idPro)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "getProfileLite");
		m.put("idProfile", idPro);
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Profile?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok") != 0) {
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("GETPROLERRORResponse",cl);
				}
				return null;
			}
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
			}
			
		} catch (Exception e) {
			Log.d("GETPROLERRORRequest",e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	public static String inviteContact(String[] contact, long idCamp)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "inviteProfiles");
		m.put("idCampaign", idCamp+"");
		
		try {
			m.put("list", Base64.encode(Crypter.serialize(contact)));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + id
					+ "&msg=" + URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("INVCONERROR","*"+cl);
				}
				return null;
			}
			
			Log.d("INVCON","ok");
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("INVCON",cl);
			}
			
		} catch (Exception e) {
			Log.d("INVCONERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	public static String inviteCommu(String[] contact, long idCommu)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();

		m.put("action", "inviteCommunities");
		m.put("idCampaign", idCommu+"");
		
		try {
			m.put("list", Base64.encode(Crypter.serialize(contact)));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if (pr.readLine().compareTo("ok") != 0) {
				while ((cl = pr.readLine()) != null) {
					sb.append(cl);
					Log.d("INVCOMERROR","*"+cl);
				}
				return null;
			}
			
			Log.d("INVCOM","ok");
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("INVCOM",cl);
			}
			
		} catch (Exception e) {
			Log.d("INVCONERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}

	public static long getId()
	{
		return Long.parseLong(id);
	}
	
	static public String downloadFile(SQLiteDatabase db, Map<String, String> m)
	{
		Socket ps;
		BufferedReader br;
		BufferedWriter pw;
		DBHelper h = new DBHelper();

		h.onCreate(db);
		Cursor c = db.query("fileInfo", null, "hash='" + m.get("hash")
				+ "' AND userid='" + id + "'", null, null, null, null);
		if(c.getCount() != 0) return "EA";  // atualizado de c.count()
		
		String hash = m.get("hash");
		
		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			br = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/files/" + hash + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
		} catch (Exception e) {
			Log.d("ERRODOWNLOAD", e.toString());
			return null;
		}

		String campCreator = m.get("campCreator");
		String size = m.get("size");
		String campName = m.get("campName");
		String filename = m.get("filename"); 
		String status =  m.get("status");
		String type = m.get("type");
		String owner = m.get("owner");
		String desc = m.get("desc");
		
		String sql = "INSERT INTO fileInfo (hash,userid,campaigncreator,size,campaignname,filename,status, type, owner, desc) VALUES ('"
			+ hash + "','" + id + "','" + campCreator + "','" + size + "','" + campName + "','" + filename + "','" + status + "','" + type + "','" + owner + "','" + desc + "');";

		db.execSQL(sql);

		String s = null;
		StringBuilder fc = new StringBuilder();
		
		try {
			while((s = br.readLine()) != null /*&& isDownloading(hash,id)*/) {
				fc.append(s);
			}
		} catch (IOException e1) {
			Log.d("ERRODOWNLOAD", e1.toString());
			try {
				ps.close();
			} catch (Exception e2) {
				Log.d("ERROCLOSING", e2.toString());
			}

			db.execSQL("UPDATE fileInfo SET status = 'Canceled' WHERE hash = '" + hash + "' AND userid='" + id + "'");
			return null;
		}

		db.execSQL("UPDATE fileInfo SET status = 'Complete' WHERE hash = '" + hash + "' AND userid='" + id + "'");
		db.execSQL("INSERT INTO fileContent (hash, content) VALUES ('" + hash + "','" + fc.toString().getBytes() + "');");

		try {
			ps.close();
		} catch (IOException e) {
			Log.d("ERROCLOSING", e.toString());
			return null;
		}
		
		return "OK";
	}

	public static String getUserName(String uid)
	{
		String resp = ServerCom.getContactInfoLite(uid);
		String sep[]=resp.split("[<>]");
		return sep[2]+" "+sep[6];
	}
	
	public static String getCampMembers(long idCamp)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();
		
		m.put("action", "getMembers");
		m.put("idCampaign", idCamp+"");
		
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Campaign?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("INVCOMERROR","*"+cl);
				}
				return null;
			}
			
			Log.d("INVCOM","ok");
						
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
				Log.d("INVCOM",cl);
			}
			
		} catch (Exception e) {
			Log.d("INVCONERROR",e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	/* Pega as N últimas mensagens da campanha.
	 * Essa função deve ser chamada ao abrir a tela do chat da campanha. As
	 * chamada seguintes devem conter um Timestamp como referência, de forma
	 * que mesmo que mais que N mensagens tenham sido enviadas entre as
	 * atualizações, todas serão trazidas.
	 */
	public static String getChatMessages(long idCamp)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();
		
		m.put("action", "init");
		m.put("campaign", Long.toString(idCamp));
		
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			pw.append("GET /JoinUs-ApplicationServer/servlets/Chat?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("CHAT","INIT Error: "+cl);
				}
				return null;
			}
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
			}
			
		} catch (Exception e) {
			Log.d("CHAT Exception", e.toString());
			return null;
		}	
		return sb.toString();
	}
	
	/* Pega as últimas mensagens da campanha desde a data lastDate, que é a data
	 * da última mensagem recebida. Ou seja, essa função pega as mensagens novas
	 * apenas.
	 */
	public static String getChatMessages(long idCamp, Timestamp lastDate){
		return sendAndGetChatMessages(idCamp, lastDate, null);
	}
	
	/* Pega as últimas mensagens da campanha desde a data lastDate, que é a data
	 * da última mensagem recebida, aproveitando a conexão e já enviando uma
	 * mensagem. Ou seja, essa função envia uma mensagem e já traz as novas.
	 */
	public static String sendAndGetChatMessages(long idCamp, Timestamp lastDate, String message)
	{
		Socket ps;
		BufferedWriter pw;
		BufferedReader pr;

		Map<String, String> m = new HashMap<String, String>();
		
		if(message != null){
			m.put("action", "send");
			m.put("msg", message);
		}else{
			m.put("action", "update");
		}
		m.put("campaign", Long.toString(idCamp));
		if(lastDate != null){
			m.put("fromDate", lastDate.toString());
		}
		
		StringBuilder sb= new StringBuilder("");

		try {
			ps = new Socket(HOST, PORT);
			pw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()), 8192);
			pr = new BufferedReader(new InputStreamReader(ps.getInputStream()), 8192);
			Log.d("Chat_Debug", "GET /JoinUs-ApplicationServer/servlets/Chat?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("GET /JoinUs-ApplicationServer/servlets/Chat?id=" + id + "&msg="
					+ URLEncoder.encode(Crypter.encrypt(key, m)) + "\n");
			pw.append("Host: " + HOST + ":" + PORT + "\n\n");
			pw.flush();
			
			String cl = null;
			
			if(pr.readLine().compareTo("ok")!=0){
				while ((cl = pr.readLine()) != null){
					sb.append(cl);
					Log.d("CHAT","UPDT Error: "+cl);
				}
				return null;
			}
			
			while ((cl = pr.readLine()) != null){
				sb.append(cl);
			}
			
		} catch (Exception e) {
			Log.d("CHAT Exception", e.toString());
			return null;
		}	
		return sb.toString();
	}
}
